In [18]:
# create an empty set
empty_set = set()
empty_set
Out[18]:
In [19]:
# create a set directly
languages = {'python', 'r', 'java'}
languages
Out[19]:
In [20]:
#create a set from a list
snakes = set(['cobra', 'viper', 'python'])
snakes
Out[20]:
In [21]:
len(languages)
Out[21]:
In [22]:
'python' in languages
Out[22]:
In [23]:
# add a new element
languages.add('sql')
languages
Out[23]:
In [24]:
# try to add an existing element (ignored, no error)
languages.add('r')
languages
Out[24]:
In [25]:
# remove an element
languages.remove('java')
languages
Out[25]:
In [26]:
# try to remove a non-existing element (this would throw an error)
# languages.remove('c')
In [27]:
# remove an element if present, but ignored otherwise
languages.discard('c')
languages
Out[27]:
In [28]:
# remove and return an arbitrary element
languages.pop()
Out[28]:
In [29]:
# remove all elements
languages.clear()
languages
Out[29]:
In [30]:
# add multiple elements
languages.update(['go', 'spark'])
languages.update({'spark', 'haskell'})
languages
Out[30]:
In [33]:
languages = {'python', 'r', 'java'}
snakes = set(['cobra', 'viper', 'python'])
In [34]:
# intersection
languages & snakes
Out[34]:
In [35]:
# union
languages | snakes
Out[35]:
In [36]:
# set difference
languages - snakes
Out[36]: